import express from 'express';
import { Card, Board, List } from '../lib/models';
import { authMiddleware } from '../middlewares/auth';
import { io } from '../startup/socket';

const router = express.Router();
router.use(authMiddleware);

// 获取卡片详情
router.get('/:id', async (req, res) => {
  try {
    const card = await Card.findById(req.params.id)
      .populate('attachments')
      .populate('subscribers', 'username profile');
    
    if (!card) {
      return res.status(404).json({ error: '卡片不存在' });
    }
    
    res.json(card);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 更新卡片
router.put('/:id', async (req, res) => {
  try {
    const updates = req.body;
    const card = await Card.findByIdAndUpdate(
      req.params.id,
      { $set: updates },
      { new: true }
    );

    io.to(card.boardId.toString()).emit('card:update', card);
    res.json(card);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 移动卡片
router.post('/:id/move', async (req, res) => {
  try {
    const { listId, position } = req.body;
    const card = await Card.findById(req.params.id);
    
    // 更新原列表
    await List.findByIdAndUpdate(card.listId, {
      $pull: { cards: card._id }
    });
    
    // 更新新列表
    await List.findByIdAndUpdate(listId, {
      $push: {
        cards: {
          $each: [card._id],
          $position: position
        }
      }
    });
    
    card.listId = listId;
    await card.save();
    
    io.to(card.boardId.toString()).emit('card:move', {
      cardId: card._id,
      listId,
      position
    });
    
    res.json(card);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

export default router; 